<?php

namespace app\common\controller;

use app\admin\model\money\Change;
use app\admin\model\product\Order;
use app\admin\model\User;
use app\admin\model\user\Finance;
use app\admin\model\user\Statics;
use app\common\model\Config;
use think\Console;

final class Bonus
{
    private static $id = 0;
    private static $user = null;
    private static $finance = null;
    private static $total = 0.00;

    public function __construct($id, $total)
    {
        self::$id = $id;
        self::$user = User::find($id);
        self::$finance = Finance::where('user_id', self::$id)->find();
        self::$total = $total;

        Config::where('name', 'achievement')->setInc('value', $total);
    }

    /**
     * 赠送积分
     * @param $number
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function giveMoney($number)
    {
        $give_money_arr = config('site.give_money');
        $multiple = 1;
        foreach ($give_money_arr as $key => $val) {
            if ($number >= $key) {
                $multiple = $val;
            }
        }

        $money = $multiple * self::$total;
        self::$finance->hasscore += $money;
        self::$finance->allscore += $money;
        self::$finance->save();

        $orderNum = create_order(self::$id);
        $mdata = [
            'order_num' => $orderNum,
            'record_type' => 1,
            'change_type' => 8,
            'moneytype' => 2,
            'money' => $money,
            'hasmoney' => self::$finance->hasscore,
//                'remark' => $tag,
            'user_id' => 0,
            'targetuserid' => self::$id
        ];

        Change::create($mdata);

        // 计算每日转化额度
        $number = Order::where('mark', 'bill')->where('user_id', self::$id)->where('status', '>=', 1)->count() + 1;
        $times = config('site.bill_times');
        if ($number <= $times) {
            $rate1 = config('site.static_first_rate') * 0.01;
            $rate2 = config('site.static_second_rate') * 0.01;
        } else {
            $rate1 = config('site.static_third_rate') * 0.01;
            $rate2 = config('site.static_four_rate') * 0.01;
        }

        $money1 = $money * $rate1;
        $money2 = $money * $rate2;

        $staticInfo = Statics::where('user_id', self::$id)->find();
        if ($staticInfo) {
            $sdata = [
                'money1' => $money1,
                'money2' => $money2,
                'total' => self::$total,
                'totaled' => 0,
            ];

            $staticInfo->save($sdata);
        } else {
            $sdata = [
                'user_id' => self::$id,
                'money1' => $money1,
                'money2' => $money2,
                'total' => $money,
                'totaled' => 0,
            ];

            Statics::create($sdata);
        }
    }

    /**
     * 推荐奖
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusRecom()
    {
        $tinfo = User::field('id,rank,tuijianid')
            ->where('id', self::$user['tuijianid'])
            ->where('rank', '>=', 1)
            ->where('status', 'normal')->find();
        if (!$tinfo) {
            return false;
        }

        $recomMoney = self::$total * config('site.recom_rate1') * 0.01;

        if ($recomMoney > 0) {
            self::bonusShare($recomMoney, 1, $tinfo['id']);
        }

        self::bonusRecom1();
    }

    /**
     * 间推奖
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusRecom1()
    {
        $tuijianids = trim(self::$user['tuijianids'], ',');
        $tinfo = User::field('id,rank,tuijianid')
            ->where('id', 'in', $tuijianids)
            ->where('rank', '>=', 1)
            ->where('status', 'normal')
            ->where('tdeep', (self::$user['tdeep'] - 2))->find();
        if (!$tinfo) {
            return false;
        }

        $number = User::where('tuijianid', $tinfo['id'])->where('rank', '>=', 1)->count();
        if ($number < 3) {
            return false;
        }

        $recomMoney = self::$total * config('site.recom_rate2') * 0.01;
        if ($recomMoney > 0) {
            self::bonusShare($recomMoney, 2, $tinfo['id']);
        }
    }

    /**
     * 分享销售收益
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusLevel()
    {
        $tuijianids = trim(self::$user['tuijianids'], ',');
        $tinfos = User::where('id', 'in', $tuijianids)
            ->where('status', 'normal')
            ->where('rank', '>=', 1)
            ->order('tdeep', 'desc')->select();
        if (!$tinfos) {
            return false;
        }

        $level = 0;
        $team_rate_arr = config('site.team_rate');

        foreach ($tinfos as $val) {
            if ($val['level'] > $level) {
                if ($level == 0) {
                    $rate = $team_rate_arr[$val['level']] * 0.01;
                } else {
                    $rate = ($team_rate_arr[$val['level']] - $team_rate_arr[$level]) * 0.01;
                }

                $leaderMoney = self::$total * $rate;
                if ($leaderMoney > 0) {
                    self::bonusShare($leaderMoney, 3, $val['id']);
                    // 平级奖
                    self::bonusPing($val['id'], $leaderMoney);
                }

                $level = $val['level'];
            }
        }
    }

    /**
     * 平级奖
     * @param $tid
     * @param $leaderMoney
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusPing($tid, $leaderMoney)
    {
        $info = User::find($tid);
        $tuijianids = trim($info['tuijianids'], ',');
        $tinfos = User::where('id', 'in', $tuijianids)
            ->where('status', 'normal')
            ->where('rank', '>=', 1)
            ->where('level', ">=", $info['level'])
            ->order('tdeep', 'desc')->select();
        if (!$tinfos) {
            return false;
        }

        $pingRate = config('site.ping_rate') * 0.01;
        $pingMoney = $leaderMoney * $pingRate;

        if ($pingMoney > 0) {
            foreach ($tinfos as $val) {
                if ($val['level'] == $info['level']) {
                    self::bonusShare($pingMoney, 4, $val['id']);
                    break;
                } elseif ($val['level'] > $info['level']) {
                    break;
                }
            }
        }
    }

    /**
     * 添加业绩
     * @return bool
     * @throws \think\Exception
     */
    public function addAchievement()
    {
        if (!self::$user->tuijianid) {
            return false;
        }

        $map = [
            'id' => ['in', trim(self::$user->tuijianids, ',')],
            'tdeep' => ['<=', (self::$user->tdeep - 2)],
            'status' => 'normal',
        ];

        User::where($map)->setInc('achievement', self::$total);
    }

    /**
     * 会员级别更新
     */
    public function bonusUpdate()
    {
        $team_update_condition = config('site.team_update_condition');
        $keys = array_keys($team_update_condition);
        $max = end($keys);
        $nteam_update_condition = [];
        foreach ($team_update_condition as $k1 => $v1) {
            $item = [
                'level' => $k1,
                'value' => $v1
            ];
            $nteam_update_condition[] = $item;
        }

        $team_update_condition3 = array_slice($nteam_update_condition, 3, 1);
        $team_update_condition56 = array_slice($nteam_update_condition, 4, 2);
        $tuijianids = trim(self::$user['tuijianids'], ',');
        $tinfos = User::where('id', 'in', $tuijianids)->where('status', 'normal')->order('tdeep', 'desc')->select();
        if (!$tinfos) {
            return false;
        }

        foreach ($tinfos as $val) {
            if ($val['level'] >= $max) {
                continue;
            }

            if ($val['level'] <= 2) {
                foreach ($team_update_condition3 as $v) {
                    if ($val['level'] < $v['level'] && $val['achievement'] >= $v['value']) {
                        User::where('id', $val['id'])->setField('level', $v['level']);
                    }
                }
            } elseif ($val['level'] == 3) {
                $achievements = User::where('tuijianid', $val['id'])->column('achievement');
                $total = array_sum($achievements);
                $max = max($achievements);
                $total -= $max;

                if ($total >= $team_update_condition3['value']) {
                    User::where('id', $val['id'])->setField('level', 4);
                }
            } else {
                $sons = User::where('tuijianid', $val['id'])->where('status', 'normal')->where('rank', '>=', 1)->select();
                foreach ($team_update_condition56 as $v1) {
                    if ($val['level'] < $v1['level']) {
                        if (count($sons) < $v1['value']) {
                            break;
                        }
                    }

                    $num = 0;
                    foreach ($sons as $v2) {
                        if ($v2['level'] >= $val['level']) {
                            $num += 1;
                            continue;
                        }
                        $count = User::where('tuijianids', 'like', '%,' . $v2['id'] . ',%')->where('level', '>=', $val['level'])->count();
                        if ($count >= 1) {
                            $num += 1;
                        }
                    }

                    if ($num >= $v1['value']) {
                        User::where('id', $val['id'])->setField('level', $v1['level']);
                    }
                }
            }
        }
    }

    /**
     * 房补
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusHouse()
    {
        $tuijianids = trim(self::$user['tuijianids'], ',');
        $tinfo = User::where('id', 'in', $tuijianids)->where('status', 'normal')->where('is_houser', 1)->order('tdeep', 'desc')->find();
        if (!$tinfo) {
            return false;
        }

        $houseRate = config('site.house_rate') * 0.01;
        $houseMoney = self::$total * $houseRate;

        if ($houseMoney > 0) {
            self::bonusShare($houseMoney, 6, $tinfo['id']);
        }
    }

    /**
     * 运营补贴
     * @return bool
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusOperat()
    {
        $tuijianids = trim(self::$user['tuijianids'], ',');
        $tinfo = User::where('id', 'in', $tuijianids)->where('status', 'normal')->where('is_operator', 1)->order('tdeep', 'desc')->find();
        if (!$tinfo) {
            return false;
        }

        $operateRate = config('site.operate_rate') * 0.01;
        $operateMoney = self::$total * $operateRate;

        if ($operateMoney > 0) {
            self::bonusShare($operateMoney, 7, $tinfo['id']);
        }
    }

    /**
     * 奖金生成
     * @param $bonusmoney
     * @param $change_type
     * @param $id
     * @param $fromuser
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function bonusShare($bonusmoney, $change_type, $tid)
    {
        $tax_rate = config('site.tax_rate');
        $dynamic_to_moneyd = config('site.dynamic_to_moneyd') * 0.01;
        $dynamic_to_shop = config('site.dynamic_to_shop') * 0.01;
        if ($tax_rate > 100 || $tax_rate <= 0) {
            $tax = 0;
        } else {
            $tax = $tax_rate * 0.01;
        }

        $tax_money = $bonusmoney * $tax;
        $actulMoney = $bonusmoney - $tax_money;
        if ($change_type <= 2) {
            $dMoney = round($bonusmoney * $dynamic_to_moneyd, 2);
            $sMoney = round($bonusmoney * $dynamic_to_shop, 2);
        } else {
            $dMoney = round($actulMoney, 2);
            $sMoney = 0;
        }

        $finance = Finance::where('user_id', $tid)->find();

        $finance->hasmoneyd += $dMoney;
        $finance->allmoneyd += $dMoney;
        if ($sMoney > 0) {
            $finance->hasshop += $sMoney;
            $finance->allshop += $sMoney;
        }

        $finance->allbonus += $bonusmoney;
        $res = $finance->save();
        if ($res) {
            self::bonus('bonus_day', $change_type, $tid, $bonusmoney, $actulMoney);
            self::bonus('bonus_total', $change_type, $tid, $bonusmoney, $actulMoney);

            $orderNum = create_order($tid);
            $mdata1 = [
                'order_num' => $orderNum,
                'record_type' => 1,
                'change_type' => $change_type,
                'moneytype' => 4,
                'money' => $dMoney,
                'hasmoney' => $finance->hasmoneyd,
//                'remark' => $tag,
                'user_id' => self::$id,
                'targetuserid' => $tid
            ];

            Change::create($mdata1);

            if ($sMoney > 0) {
                $orderNum = create_order($tid);
                $mdata2 = [
                    'order_num' => $orderNum,
                    'record_type' => 1,
                    'change_type' => $change_type,
                    'moneytype' => 5,
                    'money' => $sMoney,
                    'hasmoney' => $finance->hasshop,
//                'remark' => $tag,
                    'user_id' => self::$id,
                    'targetuserid' => $tid
                ];

                Change::create($mdata2);
            }
        }
    }

    /**
     * @param $table
     * @param $bonustype
     * @param $touser
     * @param $money
     * @param $hasmoney
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @throws \think\exception\PDOException
     */
    private function bonus($table, $bonustype, $touid, $money, $hasmoney)
    {
        $touser = User::find($touid);
        if ($table == 'bonus_day') {
            $count_date = strtotime('today');
            $map['count_date'] = $count_date;
        } else {
            $count_date = time();
        }

        $BCount = Db($table);
        $map['user_id'] = $touid;
        $bonusData = $BCount->where($map)->find();
        $field = 'bonus' . $bonustype;
        if ($bonusData) {
            $data[$field] = $bonusData[$field] + $money;
            $data['total'] = $bonusData['total'] + $hasmoney;
            $data['tax_money'] = round($money - $hasmoney, 2);
            $BCount->where($map)->update($data);
        } else {
            $data = array(
                'user_id' => $touser['id'],
                'count_date' => $count_date
            );
            $data[$field] = $money;
            $data['total'] = $hasmoney;
            $data['tax_money'] = round($money - $hasmoney, 2);
            $BCount->insert($data);
        }
    }
}